﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;
using DevExpress.Web.ASPxCallback;
using System.Net;
using System.IO;
using System.Text;
using System.Diagnostics;
using Renci.SshNet;

namespace TireService.Web.View.AdminView
{
    public partial class ManageScheduledJobs : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Page.IsPostBack != true)
            {
                
            }

            TireServiceDB db = new TireServiceDB();

            BindScheduledJobsData(db, Convert.ToInt32(ddlJob.SelectedItem.Value));
        }

        /// <summary>
        /// Function that updates gridview with scheduled jobs based on filterinput
        /// </summary>
        /// <param name="db">Connection to database</param>
        /// <param name="FilterScheduledJobs">Filter input</param>
        private void BindScheduledJobsData(TireServiceDB db, int FilterScheduledJobs) 
        {
            List<ScheduledJobQueue> jobs = new List<ScheduledJobQueue>();

            if (FilterScheduledJobs == 0)
	        {
		        // Show all jobs
                jobs = db.GetScheduledJobs();
	        }
            if (FilterScheduledJobs == 1)
            {
                // Show pending scheduled jobs
                jobs = db.GetScheduledJobsPending();
            }

            gvScheduledJobs.DataSource = jobs.OrderBy(p => p.ScheduledExecutionTime);
            gvScheduledJobs.DataBind();
        }

        /// <summary>
        /// Callback that updates gridview on client with scheduled jobs, based on selected filter
        /// </summary>
        protected void gvScheduledJobs_CustomCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomCallbackEventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            BindScheduledJobsData(db, Convert.ToInt32(e.Parameters));
        }

        /// <summary>
        /// Callback function that runs a job
        /// </summary>
        protected void callRunJob_Callback(object sender, CallbackEventArgs e)
        {
            // Get value - jobid
            int jobid = Convert.ToInt32(e.Parameter);

            TireServiceDB db = new TireServiceDB();

            // Get job
            ScheduledJobQueue job = db.GetScheduledJob(jobid);

            // Run job
            ScheduledJobs jobservice = new ScheduledJobs();
            jobservice.ExecuteJob(db, job);            
        }

        /// <summary>
        /// Callback function that deletes a job
        /// </summary>
        protected void callDeleteJob_Callback(object sender, CallbackEventArgs e)
        {
            // Get value - jobid
            int jobid = Convert.ToInt32(e.Parameter);

            TireServiceDB db = new TireServiceDB();

            // Get job
            ScheduledJobQueue job = db.GetScheduledJob(jobid);

            if (job.RealisedExecutionTime != null)
            {
                // Error - run jobs can not be deleted
                throw new ArgumentException("Job allerede kørt, kan derfor ikke slettes");
            }
            else
            {
                db.RemoveScheduledJobQueue(job);

                db.SubmitChanges();
            }

            db.Dispose();
        }

        /// <summary>
        /// Callback function that saves a new scheduled job
        /// </summary>
        protected void callbackCreateJobPanel_Callback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            // Get values from client 
            // 0: JobType, 1: Title, 2: ExecutionTime, 3: DailyRepeat (true/false)
            string[] param = e.Parameter.Split('|');

            int JobType = Convert.ToInt32(param[0]);
            string Title = param[1].ToString();
            DateTime ScheduledExecutionTime = Convert.ToDateTime(param[2]);
            bool DailyRepeat = Convert.ToBoolean(param[3]);

            ScheduledExecutionTime = ScheduledExecutionTime.AddHours(4);

            // Validate scheduledate
            if (ScheduledExecutionTime < DateTime.Now)
            {
                // Error - run jobs can not be deleted
                throw new ArgumentException("Job kan ikke oprettes i fortiden");
            }

            // Instantiate data layer
            TireServiceDB db = new TireServiceDB();

            // Create new job
            ScheduledJobQueue job = new ScheduledJobQueue();

            job.Title = Title;
            job.ScheduledExecutionTime = ScheduledExecutionTime;
            job.ScheduledJobId = JobType;
            job.DailyRepeat = DailyRepeat;

            db.AddScheduledJobQueue(job);

            // Commit changes to database
            db.SubmitChanges();

            // Dispose database connection
            db.Dispose();
        }
    }
}